using Magiq.Behaviors;
using Magiq.Delete;

namespace Magiq.Databases.Delete
{
    public class DatabaseDeleteStrategy<T> : BehaviorHandler<IDatabaseDeleteBehavior<T>>, IDeleteStrategy,
                                             IDatabaseBasedExecution where T : class
    {
        private readonly IDelete<T> delete;

        public DatabaseDeleteStrategy(IOrmAdapter ormAdapter, IDelete<T> delete)
            : base(delete.Behavior)
        {
            OrmAdapter = ormAdapter;
            this.delete = delete;
            Default<DatabaseDeleteBehavior<T>>();
        }

        #region IDatabaseBasedExecution Members

        public IOrmAdapter OrmAdapter { get; private set; }

        #endregion

        #region IDeleteStrategy Members

        public int Execute()
        {
            Call(x => x.Initialize(OrmAdapter, delete));
            var databaseDeletes = Call(x => x.BuildDatabaseDeletes());
            var result = 0;
            foreach (var databaseDelete in databaseDeletes)
            {
                var command = Call(x => x.BuildCommand(databaseDelete));
                result += command.ExecuteNonQuerySafe();
            }
            return result;
        }

        #endregion
    }
}